package com.kobe.game_60;

import java.util.List;

import com.kobe.util.MathUtil;

/**
 * 
 * The number, 1406357289, is a 0 to 9 pandigital number because it is made up
 * of each of the digits 0 to 9 in some order, but it also has a rather
 * interesting sub-string divisibility property.
 * 
 * Let d_(1) be the 1^(st) digit, d_(2) be the 2^(nd) digit, and so on. In this
 * way, we note the following:
 * 
 * d_(2)d_(3)d_(4)=406 is divisible by 2 d_(3)d_(4)d_(5)=063 is divisible by 3
 * d_(4)d_(5)d_(6)=635 is divisible by 5 d_(5)d_(6)d_(7)=357 is divisible by 7
 * d_(6)d_(7)d_(8)=572 is divisible by 11 d_(7)d_(8)d_(9)=728 is divisible by 13
 * d_(8)d_(9)d_(10)=289 is divisible by 17
 * 
 * Find the sum of all 0 to 9 pandigital numbers with this property.
 * 
 * 3265920
 */
public class _43 {

    static int[] divisions = new int[] { 2, 3, 5, 7, 11, 13, 17 };

    public static boolean hasDivisibilityProperty(int[] number) {
        int temp;
        int division = 0;
        for (int i = 1, divIndex = 0; i <= number.length - 3; i++, divIndex++) {
            division = divisions[divIndex];
            temp = 100 * number[i] + 10 * number[i + 1] + number[i + 2];
            if (temp % division != 0) {
                return false;
            }
        }
        return true;
    }

    public static long getValue(int[] number) {
        StringBuilder sb = new StringBuilder();
        for (int temp : number) {
            sb.append(temp);
        }
        return Long.parseLong(String.valueOf(sb));
    }

    public static void main(String[] args) {

        int[] pandigital = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        List<int[]> perms = MathUtil.getPerm(pandigital);

        int end = 0;
        for (int index = 0; index < perms.size(); index++) {
            if (perms.get(index)[0] == 0) {
                end = index;
            }
        }
        perms = perms.subList(end, perms.size());
        long result = 0L;
        long tempResult = 0L;
        for (int[] temp : perms) {
            if (hasDivisibilityProperty(temp)) {
                tempResult = getValue(temp);
                System.out.println(tempResult);
                result += tempResult;
            }
        }
        System.out.println("Result: " + result);
    }
}
